package me.ingxin.android.permission2.view.impl

import android.app.Activity
import android.content.Context
import android.content.ContextWrapper
import android.os.Bundle
import android.view.Gravity
import me.ingxin.android.permission2.R
import me.ingxin.android.permission2.databinding.PxDialogDefaultPermissionBinding
import me.ingxin.android.permission2.supportSpecialPermissions


/**
 * Created on 2023/7/17 by yin
 * 默认解释理由对话框和前往设置中心对话框
 * @param permissions 申请的相关权限
 * @param toSettings true表示前往设置中心，false表示展示申请理由
 */
open class DefaultReasonDialog(
    context: Context, private val permissions: List<String>, private val toSettings: Boolean = false
) : DefaultDialog(context) {

    private lateinit var binding: PxDialogDefaultPermissionBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = PxDialogDefaultPermissionBinding.inflate(layoutInflater)
        setContentView(binding.root)
        setupWindow()

        binding.positiveBtn.setOnClickListener { continueRun() }
        binding.negativeBtn.setOnClickListener { interrupt() }

        val message = getMessage(permissions, toSettings)
        if (message.isNullOrEmpty()) {
            if (toSettings) {
                binding.messageText.text = String.format(
                    context.getString(R.string.px_setting_template), getPermissionStr(permissions)
                )
            } else {
                binding.messageText.text = String.format(
                    context.getString(R.string.px_reason_template), getPermissionStr(permissions)
                )
            }
        } else {
            binding.messageText.text = message
        }

        if (toSettings) {
            binding.positiveBtn.setText(R.string.px_setting)
            binding.negativeBtn.setText(R.string.px_cancel)
        } else {
            binding.positiveBtn.setText(R.string.px_allow)
            binding.negativeBtn.setText(R.string.px_denied)
        }
    }

    /**
     * 获取权限说明
     * @param permissions 申请的权限
     * @param toSettings true表示前往设置中心，false表示展示申请理由
     * @return 返回值无效时使用默认值
     */
    protected open fun getMessage(permissions: List<String>, toSettings: Boolean): CharSequence? {
        return null
    }

    private fun setupWindow() {
        val width = context.resources.displayMetrics.widthPixels
        val height = context.resources.displayMetrics.heightPixels
        val p = if (width < height) 0.75 else 0.6
        window?.apply {
            setGravity(Gravity.CENTER)
            attributes.width = (width * p).toInt()
        }
    }

    private fun getPermissionStr(permissions: List<String>): String {
        val tempSet = HashSet<String>()
        val sb = StringBuilder()
        val pm = context.packageManager

        permissions.forEach {
            val permissionGroup = getPermissionGroup(it)
            val isSpecial = it in supportSpecialPermissions && !tempSet.contains(it)
            if (isSpecial || (permissionGroup != null && !tempSet.contains(permissionGroup))) {
                val name = if (isSpecial) {
                    getSpecialPermissionName(it)
                } else {
                    pm.getPermissionGroupInfo(permissionGroup!!, 0).loadLabel(pm)
                }
                sb.append(name)
                sb.append("、")
                tempSet.add(permissionGroup ?: it)
            }
        }
        val message = if (sb.isNotEmpty()) {
            sb.substring(0, sb.length - 1)
        } else {
            sb.toString()
        }
        return message
    }

    private fun Context.getActivity(): Activity? {
        if (this is Activity) {
            return this
        } else if (this is ContextWrapper) {
            return this.baseContext.getActivity()
        }
        return null
    }

}